<template>
  <div v-loading="loading">
    <el-form ref="queryform" :model="queryParams" :rules="rules" label-width="120px" :inline="true" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item :label="$t('科目名称')" prop="subjectCode">
            <el-select v-model="queryParams.subjectCode" filterable clearable placeholder="请选择">
              <el-option v-for="item in subjectOptions" :key="item.id" :label="item.optionName" :value="item.subjectCode" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('运算符号')" prop="oper">
            <el-select v-model="queryParams.oper" placeholder="请选择">
              <el-option v-for="item in operOption" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item :label="$t('取数规则')" prop="rule">
            <el-select v-model="queryParams.rule" filterable placeholder="请选择">
              <el-option v-for="item in ruleOption" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3">
          <el-form-item>
            <el-button type="primary" icon="el-icon-plus" size="mini" :disabled="tableLoading" @click="fetchData">{{ $t('添加') }}</el-button>
          </el-form-item>
        </el-col>
      </el-row>
      <el-table v-loading="loading || tableLoading" :data="form.dataList" style="width: 100%;margin-bottom: 20px;" border>
        <el-table-column :label="$t('科目名称')" prop="subjectName" align="left" width="380" show-overflow-tooltip />
        <el-table-column :label="$t('运算符号')" align="left" prop="oper" width="120" />
        <el-table-column :label="$t('取数规则')" align="left" prop="ruleName" />
        <template v-if="dictType==='fin_rule_income_sheet'">
          <el-table-column :label="$t('本年累计金额')" align="right" prop="yearAmount">
            <template slot-scope="scope">
              {{ formattedNumber(scope.row.yearAmount) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('本季度累计金额')" align="right" prop="quarterAmount">
            <template slot-scope="scope">
              {{ formattedNumber(scope.row.quarterAmount) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('本期金额')" align="right" prop="monthAmount">
            <template slot-scope="scope">
              {{ formattedNumber(scope.row.monthAmount) }}
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column :label="$t('期末余额')" align="right" prop="monthAmount">
            <template slot-scope="scope">
              {{ formattedNumber(scope.row.endingBalanceAmount) }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('年初余额')" align="right" prop="yearAmount">
            <template slot-scope="scope">
              {{ formattedNumber(scope.row.beginningBalanceAmount) }}
            </template>
          </el-table-column>
        </template>
        <el-table-column :label="$t('操作')" align="center" width="100">
          <template slot-scope="scope">
            <el-button size="small" type="text" icon="el-icon-delete" @click="deleteHandle(scope.$index,scope.row)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>

      </el-table>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <save-btn />
    </div>
  </div>
</template>

<script>
import {
  findAccountSubject
} from '@/api/fin/sysTemp/finSysSubjectTemp'
import {
  fetchRuleData,
  delRuleData,
  saveTempRule,
  getFinSubjectTemp
} from '@/api/fin/report/finReport'
export default {
  props: {
    dictType: {
        type: String,
        default: () => 'fin_rule_income_sheet',
        required: false
      },
    fundId: {
        type: String,
        default: () => '',
        required: false
      },
    yearMonth: {
      type: String,
      default: () => '',
      required: false
    }
    },
  data() {
    return {
      // 表单参数
      queryParams: {
        subjectCode: undefined,
        oper: undefined,
        rule: undefined,
        fundId: this.fundId,
        yearMonth: this.yearMonth,
        dictType: this.dictType
      },
      sheetType: '',
      subjectOptions: [],
      form: {
        dataList: []
      },
      addType: false,
      // 遮罩层
      loading: false,
      tableLoading: false,
      operOption: [],
      ruleOption: [],
      tempId: undefined,
      rules: {
        subjectCode: [{
          required: true,
          message: this.$t('请选择科目'),
          trigger: 'blur'
        }],
        oper: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }],
        rule: [{
          required: true,
          message: this.$t('必填信息'),
          trigger: 'blur'
        }]

      }
    }
  },
  created() {},
  methods: {
    // 初始化数据
    init(data) {
      this.loading = true
      this.addType = data.parentId === '0'
      if (data != null && data.id !== undefined) {
        this.tempId = data.id
        getFinSubjectTemp(data.id, this.fundId, this.yearMonth).then(response => {
          this.form.dataList = response.data
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      } else {
        this.reset()
        this.form.subjectType = data.parentTypes
        this.loading = false
      }
      this.initSubjectArr(this.fundId)
      this.sheetType = data.parentType
      this.form.parentId = data.parentId
      this.getDicts('fin_oper').then(response => {
        this.operOption = response.data
        if (this.operOption && this.operOption.length > 0) {
          this.queryParams.oper = this.operOption[0].dictValue
        }
      })
      this.getDicts(this.dictType).then(response => {
        this.ruleOption = response.data
        if (this.ruleOption && this.ruleOption.length > 0) {
          this.queryParams.rule = this.ruleOption[0].dictValue
        }
      })
      this.queryParams.subjectCode = undefined
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        subjectType: undefined,
        subjectName: undefined,
        subjectCode: undefined

      }
      this.resetForm('form')
    },
    // 取消按钮
    cancel() {
      this.$parent.$parent.formOpen = false
      // this.$parent.$parent.reset()
    },
    // 关闭form页面
    closeForm() {
      // 关闭form页面遮罩层
      this.loading = false
      // 关闭form页面
      if (this.$parent.$parent.formOpen !== undefined) {
        this.$parent.$parent.formOpen = false
      }
      // 刷新list页面
      if (this.$parent.$parent.getList !== undefined) {
        this.$parent.$parent.getList()
      }
    },
    /** 提交按钮 */
    submitForm() {
      if (this.form.dataList.length === 0) {
            this.msgError('请添加科目')
            return
        }
        this.loading = true
        this.form['fundId'] = this.fundId
        this.form['tempId'] = this.tempId
        saveTempRule(this.form).then(response => {
          if (response.code === 200) {
            this.msgSuccess(this.$t('保存成功'))
            this.closeForm()
          } else {
            this.msgError(response.msg)
          }
          this.loading = false
        })
    },
    initSubjectArr(fundAccountId) {
      findAccountSubject(fundAccountId).then(res => {
        this.subjectOptions = res.data
      })
    },
    addRule(data) {
      const row = {
        id: data.id,
        subjectName: data.subjectName,
        oper: data.oper,
        rule: data.rule,
        yearAmount: data.yearAmount,
        monthAmount: data.monthAmount,
        subjectCode: data.subjectCode,
        endingBalanceAmount: data.endingBalanceAmount,
        beginningBalanceAmount: data.beginningBalanceAmount,
        ruleName: data.ruleName
      }
      this.$nextTick(() => {
        this.form.dataList.push(row)
      })
    },
    deleteHandle(index, row) {
      const id = row.id
      if (id !== undefined && id !== '' && id != null) {
        this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
            confirmButtonText: this.$t('确定'),
            cancelButtonText: this.$t('取消'),
            type: 'warning'
          })
          .then(() => {
            // 调用接口
            delRuleData(id)
            this.form.dataList.splice(index, 1)
            return this.msgSuccess(this.$t('删除成功'))
          })
          .catch(function() {})
      } else {
        this.form.dataList.splice(index, 1)
      }
    },
    fetchData() {
      this.$refs['queryform'].validate(valid => {
        if (valid) {
           // 校验表格唯一
            if (!this.isSubjectCodeUnique(this.form.dataList, this.queryParams.subjectCode)) {
                this.msgWarning('科目已存在')
                return false
            } else {
              this.tableLoading = true
                fetchRuleData(this.queryParams).then(res => {
                  this.addRule(res.data)
                  this.tableLoading = false
                })
            }
        }
      })
    },
    isSubjectCodeUnique(dataList, code) {
      for (const obj of dataList) {
        if (obj.subjectCode === code) {
          return false
        }
      }
      return true
    }
  }
}
</script>
